package com.lindroid.exception

import com.mit.entity.RespResult
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.servlet.ModelAndView
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


const val ERROR_VIEW = "error"

@ControllerAdvice
class ExceptionHandler {

    /*@ExceptionHandler(Exception::class)
    fun errorHandler(request: HttpServletRequest, response: HttpServletResponse, e: Exception): Any {
        e.printStackTrace()
        return with(ModelAndView()){
            addObject("exception", e)
            addObject("url", request.requestURL)
            viewName = ERROR_VIEW
            this
        }
    }*/

    @ExceptionHandler(Exception::class)
    fun errorHandler(request: HttpServletRequest, response: HttpServletResponse, e: Exception): Any {

        e.printStackTrace()

        if (isAjax(request)){
            return RespResult(-100,"error",e.message)
        }else{
            val mav = ModelAndView()
            mav.addObject("exception", e)
            mav.addObject("url", request.requestURL)
            mav.viewName = ERROR_VIEW
            println("捕获异常")
            return mav

        }
    }


    private fun isAjax(request:HttpServletRequest) = request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString())

}